"""
报告生成工具函数
"""
import re
import json
from typing import Dict, List, Optional, Any

def extract_json_from_text(text: str) -> Optional[Dict[str, Any]]:
    """从文本中提取JSON"""
    try:
        # 尝试直接解析
        return json.loads(text)
    except json.JSONDecodeError:
        # 尝试提取JSON块
        json_pattern = r'```json\s*(.*?)\s*```'
        matches = re.findall(json_pattern, text, re.DOTALL)
        
        for match in matches:
            try:
                return json.loads(match)
            except json.JSONDecodeError:
                continue
                
        # 尝试提取花括号内容
        brace_pattern = r'\{.*\}'
        matches = re.findall(brace_pattern, text, re.DOTALL)
        
        for match in matches:
            try:
                return json.loads(match)
            except json.JSONDecodeError:
                continue
                
        return None

def validate_python_syntax(code: str) -> bool:
    """验证Python代码语法"""
    try:
        import ast
        ast.parse(code)
        return True
    except SyntaxError:
        return False

def extract_code_blocks(text: str) -> List[str]:
    """提取代码块"""
    code_pattern = r'```(?:python|py)?\s*(.*?)\s*```'
    return re.findall(code_pattern, text, re.DOTALL)

def clean_text(text: str) -> str:
    """清理文本"""
    # 移除多余的空白字符
    text = re.sub(r'\s+', ' ', text)
    # 移除首尾空白
    text = text.strip()
    return text

def generate_table_of_contents(sections: List[Dict[str, Any]]) -> str:
    """生成目录"""
    toc = "## 目录\n\n"
    for i, section in enumerate(sections, 1):
        title = section.get('title', f'第{i}章')
        toc += f"{i}. {title}\n"
    return toc

def calculate_readability_score(text: str) -> float:
    """计算可读性评分（简化版）"""
    if not text:
        return 0.0
        
    # 计算基本指标
    sentences = len(re.findall(r'[.!?]+', text))
    words = len(text.split())
    
    if sentences == 0 or words == 0:
        return 0.0
        
    # 简化的可读性评分
    avg_words_per_sentence = words / sentences
    
    # 理想的每句话词数是10-20个
    if 10 <= avg_words_per_sentence <= 20:
        score = 1.0
    elif avg_words_per_sentence < 10:
        score = avg_words_per_sentence / 10
    else:
        score = max(0.1, 1.0 - (avg_words_per_sentence - 20) / 50)
        
    return min(1.0, max(0.0, score))

def format_report_content(title: str, sections: List[Dict[str, Any]], 
                         conclusion: str = "", references: List[str] = None) -> str:
    """格式化报告内容"""
    content = f"# {title}\n\n"
    
    # 添加目录
    content += generate_table_of_contents(sections)
    content += "\n"
    
    # 添加各章节
    for i, section in enumerate(sections, 1):
        section_title = section.get('title', f'第{i}章')
        section_content = section.get('content', '')
        
        content += f"## {i}. {section_title}\n\n"
        content += f"{section_content}\n\n"
        
        # 添加代码示例
        if 'code_examples' in section:
            for code in section['code_examples']:
                content += f"```python\n{code}\n```\n\n"
    
    # 添加结论
    if conclusion:
        content += f"## 结论\n\n{conclusion}\n\n"
    
    # 添加参考文献
    if references:
        content += "## 参考文献\n\n"
        for i, ref in enumerate(references, 1):
            content += f"{i}. {ref}\n"
    
    return content

def validate_report_structure(structure: Dict[str, Any]) -> bool:
    """验证报告结构"""
    required_fields = ['title', 'sections']
    
    # 检查必需字段
    for field in required_fields:
        if field not in structure:
            return False
    
    # 检查章节结构
    sections = structure.get('sections', [])
    if not isinstance(sections, list) or len(sections) == 0:
        return False
    
    # 检查每个章节
    for section in sections:
        if not isinstance(section, dict):
            return False
        if 'title' not in section:
            return False
    
    return True 